<template>
  <div id="app">
    <router-view v-if="$route.path === '/login' || $route.path === '/register'" />
    <a-layout v-else>
      <a-layout-header class="header">
        <div class="logo">InnoClub</div>
        <div class="menu-container pc-menu">
          <a-menu
            mode="horizontal"
            :selectedKeys="[currentPath]"
            theme="dark"
            class="menu"
          >
            <a-menu-item key="/">
              <router-link to="/">首页</router-link>
            </a-menu-item>
            <a-menu-item key="/practice">
              <router-link to="/practice">练题</router-link>
            </a-menu-item>
            <a-menu-item key="/problems">
              <router-link to="/problems">刷题</router-link>
            </a-menu-item>
            <a-menu-item key="/smart-qa">
              <router-link to="/smart-qa">智能问答</router-link>
            </a-menu-item>
            <a-menu-item key="/ai">
              <router-link to="/ai">模拟面试</router-link>
            </a-menu-item>
            <a-menu-item key="/roadmap">
              <router-link to="/roadmap">资源社区</router-link>
            </a-menu-item>
            <a-menu-item key="/social">
              <router-link to="/social">动态圈子</router-link>
            </a-menu-item>
            <a-menu-item key="/relax">
              <router-link to="/relax">休息站</router-link>
            </a-menu-item>
          </a-menu>
        </div>
        <div class="menu-container mobile-only">
          <a-button class="mobile-menu-btn" @click="mobileMenuVisible = !mobileMenuVisible">
            <a-icon type="menu" />
          </a-button>
          <a-menu
            v-show="mobileMenuVisible"
            mode="vertical"
            :selectedKeys="[currentPath]"
            theme="light"
            class="mobile-menu"
          >
            <a-menu-item key="/">
              <router-link to="/">首页</router-link>
            </a-menu-item>
            <a-menu-item key="/practice">
              <router-link to="/practice">练题</router-link>
            </a-menu-item>
            <a-menu-item key="/problems">
              <router-link to="/problems">刷题</router-link>
            </a-menu-item>
            <a-menu-item key="/smart-qa">
              <router-link to="/smart-qa">智能问答</router-link>
            </a-menu-item>
            <a-menu-item key="/ai">
              <router-link to="/ai">模拟面试</router-link>
            </a-menu-item>
            <a-menu-item key="/roadmap">
              <router-link to="/roadmap">资源社区</router-link>
            </a-menu-item>
            <a-menu-item key="/social">
              <router-link to="/social">动态圈子</router-link>
            </a-menu-item>
            <a-menu-item key="/relax">
              <router-link to="/relax">休息站</router-link>
            </a-menu-item>
          </a-menu>
        </div>
        <div class="user-info">
          <template v-if="isLogin">
            <div class="message-wrapper">
              <a-badge 
                :dot="unreadCount > 0"
              >
                <a-icon 
                  type="bell" 
                  class="message-icon" 
                  @click="$router.push('/message')" 
                />
              </a-badge>
            </div>
            <a-dropdown>
              <a class="ant-dropdown-link" @click.prevent>
                <a-avatar :size="32">{{ userInfo.username?.charAt(0)?.toUpperCase() }}</a-avatar>
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="0">
                  <router-link to="/profile">个人中心</router-link>
                </a-menu-item>
                <a-menu-item key="1">
                  <router-link to="/membership">充值会员</router-link>
                </a-menu-item>
                <a-menu-item key="2" @click="handleLogout">
                  退出登录
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
          <template v-else>
            <a-button type="link" class="login-link" @click="$router.push('/login')">
              登录
            </a-button>
            <a-button type="link" class="register-link" @click="$router.push('/register')">
              注册
            </a-button>
          </template>
        </div>
      </a-layout-header>
      <a-layout-content class="main-content">
        <router-view />
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script>
import { auth } from '@/api/auth'
import { message } from '@/api/message'
import { EventBus } from '@/utils/eventBus'
import WebSocketService from '@/utils/websocket'

export default {
  name: 'App',
  data() {
    return {
      isLogin: false,
      userInfo: {},
      unreadCount: 0,
      mobileMenuVisible: false
    }
  },
  computed: {
    currentPath() {
      const path = this.$route.meta.activeMenu || this.$route.path
      return path.split('/').slice(0, 2).join('/')
    }
  },
  created() {
    // 监听登录成功事件
    EventBus.$on('loginSuccess', () => {
      this.isLogin = true
      this.checkLoginStatus()
    })
    
    // 初始化检查登录状态
    const token = localStorage.getItem('token')
    if (token) {
      this.isLogin = true
      this.checkLoginStatus()
    }

    // 监听WebSocket消息
    EventBus.$on('websocketMessage', this.handleWebSocketMessage)
    // 监听未读消息数量更新
    EventBus.$on('updateUnreadCount', (count) => {
      this.unreadCount = count
    })
  },
  beforeDestroy() {
    // 组销毁前移除事件监听
    EventBus.$off('loginSuccess', this.checkLoginStatus)
    EventBus.$off('websocketMessage', this.handleWebSocketMessage)
    EventBus.$off('updateUnreadCount')
    // 断开WebSocket连接
    WebSocketService.disconnect()
  },
  watch: {
    '$route': {
      immediate: true,
      handler() {
        this.checkLoginStatus()
      }
    }
  },
  methods: {
    async checkLoginStatus() {
      const token = localStorage.getItem('token')
      const loginId = localStorage.getItem('loginId')
      
      if (token && loginId) {
        this.isLogin = true
        await this.getUserInfo(loginId)
        // 获取未读消息数量
        this.getUnreadMessageCount()
        // 连接WebSocket
        WebSocketService.connect(loginId)
      } else {
        this.isLogin = false
        this.userInfo = {}
        this.unreadCount = 0
        // 断开WebSocket连接
        WebSocketService.disconnect()
      }
    },
    async getUserInfo(id) {
      try {
        const res = await auth.getUserInfo(id)
        this.userInfo = res.content
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 只在非401错误时处理登出
        if (!error.response || error.response.status !== 401) {
          this.handleLogout()
        } else {
          // 401错误已经被request.js处理,这里只需要清理状态
          this.isLogin = false
          this.userInfo = {}
          WebSocketService.disconnect()
        }
      }
    },
    handleLogout() {
      localStorage.removeItem('token')
      localStorage.removeItem('loginId')
      this.isLogin = false
      this.userInfo = {}
      // 断开WebSocket连接
      WebSocketService.disconnect()
      
      // 只在当前不在首页时才导航
      if (this.$route.path !== '/') {
        this.$router.push('/')
      }
      this.$message.success('已退出登录')
    },
    async getUnreadMessageCount() {
      try {
        const res = await message.getUnreadCount({
          userId: localStorage.getItem('loginId')
        })
        if (res.code === 200) {
          this.unreadCount = res.content.count
        }
      } catch (error) {
        console.error('获取未读消息数量失败:', error)
      }
    },
    handleWebSocketMessage(data) {
      // 更新未读消息数量
      this.getUnreadMessageCount()
      
      // 显示消息通知
      this.$notification.info({
        message: data.title,
        description: data.message,
        duration: 4.5,
        onClick: () => {
          // 点击通知跳转到动态详情页
          this.$router.push(`/social/${data.moment}`)
        }
      })
    }
  }
}
</script>

<style>
#app {
  font-family: -apple-system,BlinkMacSystemFont,Helvetica Neue,Arial,PingFang SC,Hiragino Sans GB,STHeiti,Microsoft YaHei,Microsoft JhengHei,Source Han Sans SC,Noto Sans CJK SC,Source Han Sans CN,sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: #fff;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 24px;
  background: #fff !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 60px;
  line-height: 60px;
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 100;
}

.logo {
  color: #1e80ff;
  font-size: 24px;
  font-weight: bold;
  width: 150px;
}

.menu-container {
  flex: 1;
  display: flex;
  justify-content: flex-start;
  margin-left: 48px;
}

.menu {
  background: transparent;
  border-bottom: none;
  line-height: 58px;
  width: auto;
}

.ant-menu-horizontal {
  border-bottom: none;
  display: flex;
  background: transparent !important;
}

.ant-menu-horizontal::before,
.ant-menu-horizontal::after {
  display: none !important;
}

.ant-menu-item {
  padding: 0 20px !important;
  margin: 0 4px !important;
  transition: all 0.2s ease;
  border: none !important;
  position: relative;
}

.ant-menu-item:hover {
  background: transparent;
}

.ant-menu-item-selected {
  background: transparent !important;
}

.ant-menu-horizontal > .ant-menu-item {
  border-bottom: none !important;
  position: relative;
}

.ant-menu-horizontal > .ant-menu-item::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 24px;
  height: 2px;
  background: transparent;
  transform: translateX(-50%);
  transition: all 0.3s;
}

.ant-menu-horizontal > .ant-menu-item-selected::after {
  background: #1e80ff;
  width: 24px;
}

.ant-menu-horizontal > .ant-menu-item:hover::after {
  background: #1e80ff;
  width: 24px;
}

.ant-menu-horizontal > .ant-menu-item a {
  color: #515767 !important;
  font-size: 15px;
  padding: 0;
}

.ant-menu-horizontal > .ant-menu-item-selected a {
  color: #1e80ff !important;
  font-weight: 500;
}

.ant-menu-dark {
  background: transparent !important;
}

.ant-menu-dark .ant-menu-item-selected {
  background: transparent !important;
}

.ant-menu.ant-menu-dark .ant-menu-item-selected {
  background: transparent !important;
}

.ant-menu-dark .ant-menu-item, 
.ant-menu-dark .ant-menu-item-group-title, 
.ant-menu-dark .ant-menu-item > a {
  color: #515767 !important;
}

.ant-menu-dark .ant-menu-item:hover, 
.ant-menu-dark .ant-menu-item-active, 
.ant-menu-dark .ant-menu-submenu-active, 
.ant-menu-dark .ant-menu-submenu-open, 
.ant-menu-dark .ant-menu-submenu-selected, 
.ant-menu-dark .ant-menu-submenu-title:hover {
  color: #1e80ff !important;
  background: transparent !important;
}

.ant-layout-content {
  min-height: calc(100vh - 60px);
  margin-top: 60px;
  padding: 0 !important;
  background: #fff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.login-link,
.register-link {
  color: #515767;
  font-size: 14px;
  padding: 0 12px;
}

.login-link:hover,
.register-link:hover {
  color: #1e80ff;
}

.ant-dropdown-link {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #515767;
}

.ant-dropdown-link:hover {
  color: #1e80ff;
}

.ant-avatar {
  background: #1e80ff;
  color: #fff;
}

.ant-dropdown-menu {
  border-radius: 2px;
}

.ant-dropdown-menu-item {
  color: #515767;
}

.ant-dropdown-menu-item:hover {
  color: #1e80ff;
  background: #f4f5f5;
}

:root {
  /* 主题色 */
  --primary-color: #1e80ff;          /* 主色调：明亮蓝色 */
  --primary-hover: #1b6fe8;          /* 主色调悬浮 */
  --primary-active: #1857dd;         /* 主色调激活 */
  
  /* 能色 */
  --success-color: #10b981;          /* 成功色：翡翠绿 */
  --warning-color: #f59e0b;          /* 警告色：橙色 */
  --error-color: #ef4444;            /* 错误色：红色 */
  --info-color: #3b82f6;             /* 信息色：蓝色 */
  
  /* 文字颜色 */
  --text-primary: #1f2937;           /* 主要文字 */
  --text-secondary: #4b5563;         /* 次要文字 */
  --text-disabled: #9ca3af;          /* 禁用文字 */
  
  /* 背景色 */
  --bg-primary: #ffffff;             /* 主背景 */
  --bg-secondary: #ffffff;           /* 次背景 */
  --bg-hover: #f9fafb;              /* 悬浮背景 */
}

/* 导航栏样式 */
.ant-layout-header {
  background: var(--bg-secondary) !important;
  border-bottom: 1px solid #e5e6eb;
}

.ant-menu-horizontal {
  border-bottom: none !important;
}

.ant-menu-horizontal > .ant-menu-item:hover::after,
.ant-menu-horizontal > .ant-menu-item-selected::after {
  border-bottom: 2px solid var(--primary-color) !important;
}

.ant-menu-horizontal > .ant-menu-item-selected a {
  color: var(--primary-color) !important;
}

.ant-menu-item:hover,
.ant-menu-item-active,
.ant-menu-submenu-active,
.ant-menu-submenu-title:hover {
  color: var(--primary-color) !important;
}

/* 按钮样式 */
.ant-btn-primary {
  background: var(--primary-color) !important;
  border-color: var(--primary-color) !important;
}

.ant-btn-primary:hover {
  background: var(--primary-hover) !important;
  border-color: var(--primary-hover) !important;
}

/* 链接和交互元素 */
a {
  color: var(--primary-color);
}

a:hover {
  color: var(--primary-hover);
}

/* 输入框和表单元素 */
.ant-input:focus,
.ant-input-focused {
  border-color: var(--primary-color) !important;
  box-shadow: 0 0 0 2px rgba(30, 128, 255, 0.2) !important;
}

/* 分页器 */
.ant-pagination-item-active {
  border-color: var(--primary-color) !important;
}

.ant-pagination-item-active a {
  color: var(--primary-color) !important;
}

/* 复选框和单选框 */
.ant-checkbox-checked .ant-checkbox-inner {
  background-color: var(--primary-color) !important;
  border-color: var(--primary-color) !important;
}

.ant-radio-checked .ant-radio-inner {
  border-color: var(--primary-color) !important;
}

.ant-radio-inner::after {
  background-color: var(--primary-color) !important;
}

/* 下拉菜单 */
.ant-dropdown-menu-item:hover {
  background-color: var(--bg-hover) !important;
  color: var(--primary-color) !important;
}

/* 标签页 */
.ant-tabs-ink-bar {
  background-color: var(--primary-color) !important;
}

.ant-tabs-tab:hover {
  color: var(--primary-hover) !important;
}

.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
  color: var(--primary-color) !important;
}

.ant-badge-dot {
  box-shadow: none !important;
  width: 6px !important;
  height: 6px !important;
  padding: 0 !important;
  background: #ff4d4f !important;
  right: 4px !important;
  top: 4px !important;
}

.message-icon {
  font-size: 20px;
  padding: 8px;
  cursor: pointer;
  color: #595959;
  transition: color 0.3s;
}

.message-icon:hover {
  color: #1e80ff;
}

.message-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

/* 移动端适配样式 */
.mobile-menu-btn {
  display: none;
  margin-right: 16px;
  border: none;
  background: transparent;
  font-size: 20px;
}

.pc-menu {
  display: block;
}

.mobile-only {
  display: none;
}

@media screen and (max-width: 768px) {
  .header {
    padding: 0 16px !important;
  }

  .logo {
    font-size: 20px !important;
    width: auto !important;
  }

  .menu-container {
    margin-left: 0 !important;
  }

  .mobile-menu-btn {
    display: block;
  }

  .menu {
    display: none !important;
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    background: white !important;
    padding: 8px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .menu.mobile-menu {
    display: block !important;
  }

  .ant-menu-item {
    display: block !important;
    width: 100% !important;
    text-align: left !important;
    padding: 12px 24px !important;
    margin: 0 !important;
    line-height: 1.5 !important;
    height: auto !important;
  }

  .ant-menu-item a {
    color: #333 !important;
  }

  .ant-menu-item-selected {
    background: #e6f7ff !important;
  }

  .ant-menu-item-selected a {
    color: #1890ff !important;
  }

  .ant-menu-horizontal {
    line-height: inherit !important;
  }

  .ant-menu-horizontal > .ant-menu-item::after {
    display: none !important;
  }

  .user-info {
    margin-left: auto;
  }

  .pc-menu {
    display: none;
  }

  .mobile-only {
    display: block;
  }

  .mobile-menu {
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    background: white !important;
    padding: 8px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .mobile-menu-btn {
    display: block;
    margin-right: 16px;
    border: none;
    background: transparent;
    font-size: 20px;
  }

  .ant-menu-item {
    display: block !important;
    width: 100% !important;
    text-align: left !important;
    padding: 12px 24px !important;
    margin: 0 !important;
    line-height: 1.5 !important;
    height: auto !important;
  }

  .ant-menu-item a {
    color: #333 !important;
  }

  .ant-menu-item-selected {
    background: #e6f7ff !important;
  }

  .ant-menu-item-selected a {
    color: #1890ff !important;
  }
}
</style>
